package controllers

import (
	//"bytes"
	//"encoding/json"
	//"fmt"
	"log"
	//"myk8s/common"
	m "myk8s/models"
	"strings"

	//"github.com/tidwall/gjson"

	beego "github.com/beego/beego/v2/server/web"
)

type DeployController struct {
	beego.Controller
}

func (this *DeployController) List() {
	clusterId := this.GetString("clusterId")
	nameSpace := this.GetString("nameSpace")
	deployName := this.GetString("deployName")
	labels := this.GetString("labels")
	labelsKV := strings.Split(labels, ":")
	var labelsKey, labelsValue string
	if len(labelsKV) == 2 {
		labelsKey = labelsKV[0]
		labelsValue = labelsKV[1]
	}

	depList, err := m.DeployList(clusterId, nameSpace, deployName, labelsKey, labelsValue)
	msg := "success"
	code := 0
	count := len(depList)
	if err != nil {
		msg = err.Error()
		code = -1
	}

	this.Data["json"] = &map[string]interface{}{"code": code, "msg": msg, "count": count, "data": &depList}
	this.ServeJSON()
}

func (this *DeployController) Create() {
	clusterId := this.GetString("clusterId")
	code := 0
	msg := "success"
	err := m.DeployCreate(clusterId, this.Ctx.Input.RequestBody)
	if err != nil {
		code = -1
		msg = err.Error()
		log.Printf("[ERROR] Deploy Create Fail:%s\n", err)
	}
	this.Data["json"] = &map[string]interface{}{"code": code, "msg": msg}
	this.ServeJSON()
}

func (this *DeployController) Yaml() {
	clusterId := this.GetString("clusterId")
	namespace := this.GetString("nameSpace")
	deployName := this.GetString("deployName")

	yamlStr, _ := m.GetDeployYaml(clusterId, namespace, deployName)
	this.Ctx.WriteString(yamlStr)
}

func (this *DeployController) Restart() {
	clusterId := this.GetString("clusterId")
	namespace := this.GetString("nameSpace")
	deployName := this.GetString("deployName")

	code := 0
	msg := "success"
	err := m.DeployRestart(clusterId, namespace, deployName)
	if err != nil {
		log.Println(err)
		code = -1
		msg = err.Error()
	}
	this.Data["json"] = &map[string]interface{}{"code": code, "msg": msg}
	this.ServeJSON()
}
